﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SimpleData.ObjectModel
{
	internal sealed class DataObjectNameParser
	{
		// @"[\w_-]+"
		private const string NamePattern = @"[\w_-]+";
		// @"[\w_-]+(\.[\w_-]+)*";
		private const string NamespacePattern = NamePattern + @"(\." + NamePattern + ")*";
		// (?<fullname>(?<ns>[\w_-]+(\.[\w_-]+)*)\[(?<name>[\w_-]+)\])
		private const string FullNamePattern = @"^(?<fullname>(?<ns>" + NamespacePattern + @")\[(?<name>" + NamePattern + @")\])$";

		private const string OnlyNamespacePattern = "^(?<onlyns>" + NamespacePattern + ")$";
		private const string OnlyNamePattern = "^(?<onlyname>" + NamePattern + ")$";

		private static readonly Regex fieldParser = new Regex( FullNamePattern, RegexOptions.IgnoreCase | RegexOptions.Compiled );
		private static readonly Regex onlyNameParser = new Regex( OnlyNamePattern, RegexOptions.IgnoreCase | RegexOptions.Compiled );


		internal static TDataObject TryParse<TDataObject>( string input, Func<string, string, TDataObject> factory )
		{
			Match match = fieldParser.Match( input );

			if ( match != null && match.Success )
			{
				string ns = match.Groups[ "ns" ].Value;
				string name = match.Groups[ "name" ].Value;

				return factory( ns, name );
			}
			else
				return default( TDataObject );
		}

		internal static bool IsOnlyName( string name )
		{
			return onlyNameParser.IsMatch( name );
		}

		internal static bool IsFullName( string input )
		{
			return fieldParser.IsMatch( input );
		}
	}
}
